const fs = require("fs");
const child_process = require("child_process");
const pkg = require("./package.json");

function exec(cmd, savepid) {
	return new Promise(function (resolve, reject) {
		console.log(cmd);
		let proc = child_process.exec(cmd, function (err, stdout, stderr) {
			if (err) {
				reject(err);
			} else {
				resolve(stdout);
			}
		});
		proc.stdout.pipe(process.stdout);
		proc.stderr.pipe(process.stderr);
	});
}

async function main() {
	if (!(await fs.existsSync("data/config.json"))) {
		fs.mkdirSync("data");
		return console.error("请先配置 data/config.json");
	}
	await exec(`npm install`);
	await exec(`node dist/bin/greendb merge --force`);
	let text = fs.readFileSync("data/config.json", "utf8");
	const cjson = require("comment-json");
	let cfg = cjson.parse(text);
	if (cfg.admin) {
		await exec(`node dist/bin/greendb init ${cfg.admin.account} ${cfg.admin.password}`);
	}
	console.log("初始化完成");
	if (process.argv.indexOf("--run") < 0) {
		console.log(`手动启动 node dist/app.js`);
		console.log(`pm2启动 pm2 start dist/app.js --name ${pkg.name}`);
		console.log(`pm2重启 pm2 reload ${pkg.name}`);
		return;
	}
	console.log("启动服务");
	await exec(`node dist/app.js`);
}

main().catch(console.error);
